import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,Pagination ,Toast ,Button,TextareaItem,WhiteSpace,ActivityIndicator} from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail} from '../../utils/Validator.js'
import PropTypes from 'prop-types';
class StoresCreate extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:true,
      anim:false,
      new_region:undefined
		}
	}
  getServer(){
    let _this = this;
    reqwest({
      url: window.host+'/api/pres',
      method: 'get',
      crossOrigin: true,
      // headers:AUTH_KEY,
      // contentType: 'application/json',
      data:{
        access_token:window.localStorage['token']
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      this.setState({reginos:data.regions})
    }).fail( (err, msg) =>{
       console.log(1)
       // this.setState({loading:true});
    })
  }
	loadServer(params={}){
		// console.log(data)
		reqwest({
      url: window.host+'/api/stores',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{ access_token:localStorage['token'],
        region:{name:params.region},
        store:{name:params.store.name,region_id:params.store.region_id,contact:params.store.contact,phone:params.store.phone,address:params.store.address}},
    }).then((data) => {
      if(data.status=='success'){
          Toast.success(
          '保存成功',
          1,
          ()=>{
            // window.localStorage['token']=data.token;
            // window.localStorage['curloe']=data.current_user.role;
            // // debugger
            // window.localStorage['menu']=JSON.stringify(data.menu);
            // window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            // window.localStorage['account_type']=data.current_user.account_type;
            // window.localStorage['userrr_id']=data.current_user.id;
            window.location.hash='/hfive/stores';
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
  AddRegions(e,region){
    // e.preventDefault();
    this.setState({anim:true})
    let _channels = this.state.reginos;
    let _this = this;
    // let value = e.target.value;
    console.log(this.state.pressEnter)
    // return
    if(this.state.pressEnter==undefined){
      return
    }
    reqwest({
      url: window.host+'/api/stores/add_region',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        region_name:_this.state.pressEnter,
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      if(data.status=="success"){
        _channels.push(data.data)
        _this.setState({reginos:_channels,new_region:[data.data.id],visible:false});
        window.sessionStorage['regions']=JSON.stringify(_channels);
        Toast.success('新建渠道成功', 0.5,()=>{ 
          this.setState({anim:false})
        })
      }else{
        Toast.fail(data.msg,1)
        this.setState({anim:false})
      }
    }).fail( (err, msg) =>{
      message.fail('服务器连接失败',0.5)
      this.setState({anim:false})
      console.log(1)
    })
  }
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
      if (!err  ) {
        console.log('Received values of form: ', values);
      	_this.loadServer({
      	 	channel:{name:values.resetcha},
      	 	region:values.chaname,
      	 	store:{name:values.cha_name,region_id:values.regioname[0],contact:values.contact,phone:values.phone,address:values.address},
      	})
      }
    });
	}
	componentWillMount(){
		// let _regions=[];
		// if(!!sessionStorage['regions']){
		// 	JSON.parse(sessionStorage['regions']).map(function(data,index){
		// 		_regions.push({
		// 			value:data.id,
		// 			label:data.name
		// 		})
		// 	})
		// }
		// this.setState({reginos:_regions})
    this.getServer();
	}
	render(){
    let _regions=[]
    this.state.reginos.map(function(data,index){
        _regions.push({
          value:data.id,
          label:data.name
        })
      })
    console.log(this.state.new_region)
		 const { getFieldProps , getFieldError} = this.props.form;
		 const _this =this;
		 return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '渠道/门店信息'}>
					<Picker  className={`${Reset.tel_picker}`} cols={1} extra={<span>选择渠道</span>} style={{textAlign:'left'}} clear
	          	error={!!getFieldError('regioname')}
		          onErrorClick={() => {
		            alert(getFieldError('regioname').join('、'));
		          }}
	            placeholder="选择渠道" 
		          onOk={(e)=>{this.setState({disable:false,new_region:e});console.log(e)}}
		          {...getFieldProps('regioname',{
                // initialValue:[_this.state.new_region],
              })}  title="选择渠道"  data={_regions} value={this.state.new_region}  >
	          <List.Item arrow="horizontal"
	          	className={`${Reset.list_extra} ${Reset.tel_input}`}
	          >选择渠道</List.Item>
	        </Picker>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('chaname')}
            onErrorClick={() => {
              alert(getFieldError('chaname').join('、'));
            }}
            {...getFieldProps('chaname',{
              rules:[{required:this.state.disable}]
            })}
            placeholder="其他渠道"
            value={this.state.pressEnter}
            extra={<a onClick={()=>{this.AddRegions()}}><ActivityIndicator animating={this.state.anim} />保存</a>}
            onChange={(e)=>this.setState({pressEnter:e})}
          >其他渠道</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('cha_name')}
	          onErrorClick={() => {
	            alert(getFieldError('cha_name').join('、'));
	          }}
            {...getFieldProps('cha_name',{
            	rules:[{required:true,message:'请输入门店名称'}]
            })}
            placeholder="请输入门店名称"
          >门店名称</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('contact')}
	          onErrorClick={() => {
	            alert(getFieldError('contact').join('、'));
	          }}
            {...getFieldProps('contact',{
            	rules:[{required:true,message:'请输入联系人'}]
            })}
            placeholder="联系人"
          >联系人</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('phone')}
	          onErrorClick={() => {
	            alert(getFieldError('phone').join('、'));
	          }}
            {...getFieldProps('phone',{
            	rules:[{required:true,message:'请输入手机号码',validator:(rule,value,callback)=>{
								!!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
							}}]
            })}
            placeholder="手机号码"
          >手机号码</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('address')}
	          onErrorClick={() => {
	            alert(getFieldError('address').join('、'));
	          }}
            {...getFieldProps('address',{
            	rules:[{required:true,message:'请输入地址'}]
            })}
            placeholder='地址'
          >地址</InputItem>
          <List className={`${Reset.tel_list_header}`} renderHeader={() => '备注'} style={{background:'#f5f5f9'}}>
	          <TextareaItem
               className={`${Reset.tel_textarea}`}
	            {...getFieldProps('remark', {
	              initialValue: '备注'
	            })}
	            rows={5}
	            count={100}
	          />
	        </List>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const StoresForm = createForm()(StoresCreate);
export default connect()(StoresForm)